﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhiJiao.Dal;
using ZhiJiao.Models.Entities;
using ZhiJiao.Service.Abstracts;
using ZhiJiao.Service.Dto;
using ZhiJiao.Service.FilterDto;

namespace ZhiJiao.Service.Services
{
    /// <summary>
    /// 机构服务
    /// </summary>
    public class InstructionService:IInstructionService
    {
        private readonly BackJson res;
        private readonly ZJDbContext _db;
        private readonly IdWorker _idWorker;
        public InstructionService(BackJson backJson, ZJDbContext zJDbContext)
        {
            res = backJson;
            _db = zJDbContext;
            _idWorker = SnowflakeUtil.CreateIdWorker();
        }

        
        /// <summary>
        /// 添加机构
        /// </summary>
        public BackJson AddSubmit(AddInstructionDto model)
        {
            User user = null;
            if (!string.IsNullOrEmpty( model.ControlUserId) )
            {
                user = _db.Users.FirstOrDefault(u => u.Id == model.ControlUserId);
            };

            var ins = new Instruction {
                Name = model.Name!,
                Address = model.Address!,
                ControlUser = user,
                LinkPhone = model.LinkPhone!,
                IsActive = model.IsActive,
                CreatedTime=DateTime.Now
            };
            _db.Add(ins);
            _db.SaveChanges();

            res.code = 0;
            res.msg = "添加成功";

            return res;
        }

        /// <summary>
        /// 修改机构信息
        /// </summary>
        public BackJson EditSubmit(AddInstructionDto model)
        {
            try
            {
                var ins = _db.Instructions.First(i => i.Id == model.Id);
                ins.Address = model.Address!;
                ins.Name = model.Name!;
                ins.LinkPhone = model.LinkPhone!;
                ins.IsActive = model.IsActive;
                ins.ControlUser = _db.Users.FirstOrDefault(u => u.Id == model.ControlUserId);
                ins.UpdatedTime = DateTime.Now;
                _db.Instructions.Update(ins);
                _db.SaveChanges();
                res.code = 0;
                res.msg = "机构信息保存成功";
            }
            catch (Exception ex) 
            {
                res.code = 1;
                res.msg= ex.Message;
            }
            return res;
        }

        /// <summary>
        /// 删除
        /// </summary>
        public BackJson Delete(long id)
        {
            try
            {
                var ins = _db.Instructions.First(i => i.Id == id);
                _db.Instructions.Remove(ins);
                _db.SaveChanges();
                res.code = 0;
                res.msg = "机构删除成功！";
            }
            catch (Exception e)
            {
                res.code = 1;
                res.msg= e.Message;
            }
            return res;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public BackJson GetList(InsFilter filter) 
        {
            List<Instruction> list = _db.Instructions.OrderByDescending(i=>i.CreatedTime) .ToList();
            if (filter.IsActive != null  )
            {
                list = list.Where(i => i.IsActive == filter.IsActive).ToList();
            }
            if (!string.IsNullOrEmpty(filter.InstructionName))
            {
                list = list.Where(i => i.Name.Contains(filter.InstructionName)).ToList();
            }
            var data = list.Select(i => new
            {
                id=i.Id,
                name=i.Name,
                address=i.Address,
                linkPhone=i.LinkPhone,
                controlUserId=i.ControlUser?.Id,
                controlUserName=i.ControlUser?.NormalizedUserName,
                isActive = i.IsActive,
                createTime=i.CreatedTime.ToString("yyyy-MM-dd")
            });
            res.data= data;
            res.code = 0;
            res.msg = "获取机构列表成功";
            return res;
        }
    }
}
